import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import BlogList from '../views/BlogList.vue'
import BlogEdit from '../views/BlogEdit.vue'
import BlogCreate from '../views/BlogCreate.vue'
import CategoryList from '../views/CategoryList.vue'
import UserList from '../views/UserList.vue'
import FileList from '@/views/FileList.vue'

const routes = [
  { path: '/login', name: 'Login', component: Login },
  { path: '/', name: 'Home', component: Home, redirect: '/blogs',
    children: [
      { path: '/blogs', name: 'BlogList', component: BlogList },
      { path: '/blogs/create', name: 'BlogCreate', component: BlogCreate },
      { path: '/blogs/edit/:id', name: 'BlogEdit', component: BlogEdit },
      { path: '/categories', name: 'CategoryList', component: CategoryList },
      { path: '/users', name: 'UserList', component: UserList },
      { path: '/files', name: 'FileList', component: FileList,
        meta: {
          title: '文件管理'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否登录（这里使用localStorage模拟，实际项目中应该使用Pinia/Vuex存储）
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  // 如果未登录且需要授权访问，则重定向到登录页
  if (isLoggedIn) {
    next()
  }


  if (to.path == "/login") {
    next();
  } else {
    next({ path: "/login" }); //跳转页面到login页
  }
})

export default router